using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Castle.Windsor;
using Web.HelperClasses;

namespace Web.Extensions
{
	public class WindsorFilterAttributeFilterProvider : FilterAttributeFilterProvider
	{
		IWindsorContainer container;

		public WindsorFilterAttributeFilterProvider(IWindsorContainer container)
		{
			this.container = container;
		}

		protected override IEnumerable<FilterAttribute> GetControllerAttributes(ControllerContext controllerContext,
																				ActionDescriptor actionDescriptor)
		{
			var attributes = base.GetControllerAttributes(controllerContext, actionDescriptor);
			foreach (var attribute in attributes)
			{
				container.InjectProperties(attribute, true);
			}
			return attributes;
		}

		protected override IEnumerable<FilterAttribute> GetActionAttributes(ControllerContext controllerContext,
																			ActionDescriptor actionDescriptor)
		{
			var attributes = base.GetActionAttributes(controllerContext, actionDescriptor);
			foreach (var attribute in attributes)
			{
				container.InjectProperties(attribute, true);
			}
			return attributes.Concat(ConstructGlobalFilters());
		}

		public IEnumerable<FilterAttribute> ConstructGlobalFilters()
		{
			var inflectorFilter = new InflectorActionFilterAttribute();
			var wordFormatterFilter = new WordFormatterActionFilterAttribute();
			container.InjectProperties(inflectorFilter);
			container.InjectProperties(wordFormatterFilter);
			return new ActionFilterAttribute[] { inflectorFilter, wordFormatterFilter };
		}
	}
}
